package com.sharedmobility.servlet;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sharedmobility.dao.PaymentDAO;
import com.sharedmobility.dao.TripDAO;
import com.sharedmobility.dao.UserDAO;
import com.sharedmobility.model.Payment;
import com.sharedmobility.model.Trip;
import com.sharedmobility.model.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Map;
import java.lang.reflect.Type;
import java.util.HashMap;

@WebServlet("/api/payment")
public class PaymentServlet extends HttpServlet {
    private TripDAO tripDAO;
    private UserDAO userDAO;
    private PaymentDAO paymentDAO;
    private Gson gson;
    private static final Type MAP_TYPE = new TypeToken<Map<String, Object>>(){}.getType();

    @Override
    public void init() throws ServletException {
        tripDAO = new TripDAO();
        userDAO = new UserDAO();
        paymentDAO = new PaymentDAO();
        gson = new Gson();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 获取当前登录用户ID
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            
            if (userId == null) {
                throw new Exception("用户未登录");
            }

            // 获取请求参数
            Map<String, Object> requestData = gson.fromJson(request.getReader(), MAP_TYPE);
            Integer tripId = ((Number) requestData.get("tripId")).intValue();
            String cardNumber = (String) requestData.get("cardNumber");
            String expiryDate = (String) requestData.get("expiryDate");
            String cvv = (String) requestData.get("cvv");

            // 验证支付信息
            if (!validateCard(cardNumber, expiryDate, cvv)) {
                throw new Exception("支付信息无效");
            }

            // 获取行程信息
            Trip trip = tripDAO.findById(tripId);
            if (trip == null) {
                throw new Exception("行程不存在");
            }
            if (!trip.getUserId().equals(userId)) {
                throw new Exception("无权支付此行程");
            }
            if (trip.getStatus() != 2) {
                throw new Exception("只能支付已完成的行程");
            }
            if (trip.getPaid()) {
                throw new Exception("该行程已支付");
            }

            // 计算需要支付的金额
            BigDecimal amount = trip.getCost();
            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                throw new Exception("无效的支付金额");
            }

            // 创建支付记录
            Payment payment = new Payment();
            payment.setUserId(userId);
            payment.setTripId(tripId);
            payment.setAmount(amount);
            payment.setMethod("信用卡");
            payment.setStatus(1); // 1表示支付成功
            payment.setCreatedAt(new Timestamp(System.currentTimeMillis()));

            // 保存支付记录
            boolean paymentCreated = paymentDAO.create(payment);
            if (!paymentCreated) {
                throw new Exception("创建支付记录失败");
            }

            // 更新行程支付状态
            boolean success = tripDAO.updatePaymentStatus(tripId, true);
            if (!success) {
                throw new Exception("更新支付状态失败");
            }

            // 返回成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "支付成功");
            result.put("data", payment);
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            // 返回错误响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }

    private boolean validateCard(String cardNumber, String expiryDate, String cvv) {
        // 验证卡号格式（简单示例）
        if (cardNumber == null || !cardNumber.matches("\\d{16,19}")) {
            return false;
        }

        // 验证有效期格式（MM/YY）
        if (expiryDate == null || !expiryDate.matches("(0[1-9]|1[0-2])/([0-9]{2})")) {
            return false;
        }

        // 验证CVV格式（3位数字）
        if (cvv == null || !cvv.matches("\\d{3}")) {
            return false;
        }

        return true;
    }
} 